<template>
    <div class="file">
        <div class="header">

            <el-button class="headerBtn" @click="back"><i class="el-icon-back"></i></el-button>
            <div class="path">{{ path }}</div>
            <el-button class="headerBtn" @click="initDir"><i class="el-icon-refresh-right"></i></el-button>
        </div>
        <div class="btns">
            <el-button-group>
                <el-button type="primary" @click="openBuild">新建文件夹</el-button>
                <el-popconfirm confirm-button-text='好的' cancel-button-text='不用了' style="margin:0 10px"
                    icon="el-icon-info" icon-color="red" title="确定删除？" @confirm="deleteFile">
                    <el-button type="danger" slot="reference" icon="el-icon-delete"></el-button>
                </el-popconfirm>
                <el-button @click="download">下载</el-button>
                <el-button @click="startUpload">上传</el-button>
                <el-button type="success" @click="initDir">刷新</el-button>
            </el-button-group>
            <el-checkbox style="backgroundColor:white" @change="changeVisible" v-model="visibility" label="显示隐藏文件"
                border></el-checkbox>
        </div>
        <el-table :data="tableData" tooltip-effect="dark" style="width: 100%" border v-loading="tableLoading"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="100">
            </el-table-column>
            <el-table-column label="文件名" width="320">
                <template class="filenameBox" slot-scope="scope">
                    <i class="fileIcon el-icon-folder" v-if="scope.row.filetype === 'dir'"></i>
                    <i class="fileIcon el-icon-picture-outline" v-if="scope.row.filetype === 'png'"></i>
                    <i class="fileIcon el-icon-document" v-if="scope.row.filetype === 'txt'"></i>
                    <i class="fileIcon el-icon-question" v-if="scope.row.filetype === 'unknown'"></i>
                    <div @dblclick="enterDir(scope.row)" @click="enterDir(scope.row)" class="filename">{{
                            scope.row.filename
                    }}</div>
                </template>
                <!-- 这里为什么必须用插槽呢？ -->
            </el-table-column>
            <el-table-column prop="filesize" label="大小" width="120">
            </el-table-column>
            <el-table-column prop="filetime" label="创建时间" width="220">
            </el-table-column>
            <el-table-column  label="更多操作" >
                <template slot-scope="scope">
                    <span class="options" @click="opacity(scope)">隐藏文件</span>｜ <span @click="inopacity(scope)" class="options">取消隐藏</span>｜<span class="options">删除</span>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog title="上传文件" :visible.sync="uploadDialog" width="40%">
            <input @change="changeUploadFiles($event)" multiple="multiple" type="file" class="fileUpload" />
        </el-dialog>
    </div>
</template>
<script>
import Axios from 'axios';
import { fileDownLoad } from "@/utils/fileDownLoad"
export default {
    data() {
        return {
            tableData: [],
            tableLoading: false,
            path: "/test1",//当前文件路径
            checkFilesArray: [],
            visibility: false,//是否显示隐藏文件
            uploadFileList: [],//上传文件列表
            uploadDialog: false,
        }
    },
    mounted() {
        // let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NzAyMzYyMTEsImlzcyI6ImNhYmNsYWIiLCJ1c2VyX25hbWUiOiJ0ZXN0MSIsInVzZXJfaWQiOjE2NjU3MzkzMTY3MjEsInVzZXJfcm9sZSI6MH0.oppX_QBaX0k6klpVpaQXBvM4SZ3WCM25K8paxlYl35A";
        // Axios.defaults.headers.common['Authorization'] = token;
        this.initDir();
    },
    methods: {
        initDir() {
            let way = this.visibility === true ? 1 : 0;
            this.tableLoading = true;
            //初始化列表
            Axios({
                method: 'post',
                data: JSON.stringify({ path: this.path, way }),
                url: 'http://c7.cabc.top:8222/api/v1.0/jwt/filesystem/getdir/',
                headers: {
                    "Content-Type": "application/json"
                }
            })
                .then((res) => {
                    this.tableLoading = false;
                    if (res.data.code === "0") {
                        this.tableData = res.data.data.files;
                    } else {
                        this.$message.error("获取文件失败！")
                    }
                }).catch((err) => {
                    this.tableLoading = false;
                    this.$message.error("获取文件失败！")
                    console.log(err);
                });
        },
        openBuild() {
            //创建文件前置函数
            this.$prompt('请输入文件名', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                this.buildNewDir(value)
            }).catch(() => {
                this.$message.info("取消输入")
            })
        },
        buildNewDir(val) {
            Axios({
                url: "http://c7.cabc.top:8222/api/v1.0/jwt/filesystem/mkdir/",
                method: "post",
                data: JSON.stringify({ path: this.path, name: val }),
                headers: {
                    "Content-Type": "application/json"
                }
            }).then((res) => {
                console.log(res);
                if (res.data.code === "0") {
                    this.$message.success("创建成功！");
                    this.initDir();
                } else {
                    this.$message.error(res.data.data);
                }
            }).catch((err) => {
                this.$message.error("创建文件夹失败！")
                console.log(err);
            });
        },
        enterDir(scope) {
            console.log(scope);
            if (scope.filetype !== "dir") {
                return;
            }
            this.path += ("/" + scope.filename);
            this.initDir();
        },
        back() {
            let pathArr = this.path.split("/")
            if (pathArr[0] === "" && (pathArr.length === 1 || pathArr.length === 2)) return;
            pathArr.pop();
            this.path = pathArr.join("/")
            this.initDir();
        },
        changeUploadFiles(event) {
            this.uploadFileList = [];
            this.uploadFileList = event.target.files
            this.upload()
            //上传文件选择框改变时的响应函数
        },
        startUpload(){
            //打开上传窗口
            this.uploadDialog = true;
        },
        upload() {
            if (this.uploadFileList.length === 0) {
                this.$message.error("你还没有选择文件！")
                this.uploadDialog = false;
                return;
            }
            //处理文件
            let formData = new FormData()
            let file = this.uploadFileList;
            for (let i = 0; i < file.length; i++) {
                formData.append('files', file[i], file[i].name)
            }
            formData.append('path',this.path)
            console.log(formData.get('files'))
            Axios({
                method:"post",
                url:'http://c7.cabc.top:8222/api/v1.0/jwt/filesystem/uploadfile/',
                headers:{
                    'Content-Type': 'multipart/form-data;charset=UTF-8'
                },
                data:formData
            }).then((res) => {
                console.log(res);
            }).catch((err) => {
                console.log(err);
            });

        },
        download() {
            if (this.checkFilesArray.length === 0) {
                this.$message.error("请选中你要操作的文件。");
                return;
            }
            for (let i in this.checkFilesArray) {
                if (this.checkFilesArray[i].filetype === "dir") {
                    this.$message.error("文件夹不支持下载！")
                    return;
                }
                Axios({
                    method: 'post',
                    url: 'http://c7.cabc.top:8222/api/v1.0/jwt/filesystem/downloadfile/',
                    headers: {
                        "Content-Type": "application/json"
                    },
                    responseType: 'blob',
                    data: {
                        path: this.path,
                        name: this.checkFilesArray[i].filename,
                    }
                }).then((res) => {
                    console.log(res);
                    if (res.data) {
                        let name = `${this.checkFilesArray[i].filename}.${this.checkFilesArray[i].filetype}`
                        fileDownLoad(res.data, name);
                    } else {
                        this.$message.error("文件下载失败！")
                    }
                }).catch((err) => {
                    console.log(err);
                    this.$message.error("文件下载失败！")
                });
            }
        },
        deleteFile() {
            if (this.checkFilesArray.length === 0) {
                this.$message.error("请选中你要操作的文件。");
                return;
            }
            for (let i in this.checkFilesArray) {
                Axios({
                    method: 'post',
                    url: 'http://c7.cabc.top:8222/api/v1.0/jwt/filesystem/deldir/',
                    headers: {
                        "Content-Type": "application/json"
                    },
                    data: {
                        path: this.path,
                        name: this.checkFilesArray[i].filename,
                        type: this.checkFilesArray[i].filetype,
                    }
                }).then((res) => {
                    console.log(res);
                    if (res.data.code === "0") {
                        this.$message.success(`${this.checkFilesArray[i].filename}删除成功`)
                        this.initDir();
                    } else {
                        this.$message.error(res.data.message)
                    }
                }).catch((err) => {
                    this.$message.error("删除失败！")
                    console.log(err);
                });
            }

        },
        handleSelectionChange(val) {
            //选中表格时的触发函数
            this.checkFilesArray = val;
        },
        changeVisible() {
            //显示是否隐藏文件
            this.initDir()
        },
        opacity(event){
            //隐藏文件
            Axios({
                url:'http://c7.cabc.top:8222/api/v1.0/jwt/filesystem/sethide/',
                method:'post',
                data:{
                    path:this.path,
                    name:event.row.filename,
                }
            }).then((res) => {
                console.log(res);
                if(res.data.code === "0"){
                    this.$message.success(res.data.message)
                    this.initDir();
                }else{
                    this.$message.error(res.data.message)
                }
            }).catch((err) => {
                this.$message.error("操作失败！")
                console.log(err);
            });
        },
        inopacity(event){
            //不隐藏文件
            Axios({
                url:'http://c7.cabc.top:8222/api/v1.0/jwt/filesystem/cancelhide/',
                method:'post',
                data:{
                    path:this.path,
                    name:event.row.filename,
                }
            }).then((res) => {
                console.log(res);
                if(res.data.code === "0"){
                    this.$message.success(res.data.message)
                    this.initDir();
                }else{
                    this.$message.error(res.data.message)
                }
            }).catch((err) => {
                this.$message.error("操作失败！")
                console.log(err);
            });
        
        }
    }
}
</script>
<style scoped>
.file {
    width: 90%;
    margin: 50px auto;
}

.btns {
    display: flex;
    justify-content: flex-end;
    padding: 20px 0;
    /* border: 1px solid black; */
}

.filename {
    cursor: pointer;
}

.filename:hover {
    color: rgb(195, 0, 0);
}

.fileIcon,
.filename {
    display: inline;
}

.fileIcon {
    margin: 0 5px;
    font-size: large;
}

.header {
    display: flex;
}

.headerBtn {
    width: 40px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.path {
    flex: 1;
    color: darkgray;
    background-color: white;
    padding: 0 10px;
    border: 1px solid rgb(207, 207, 207);
    border-radius: 3px;
    font-size: small;
    font-weight: 400;
    line-height: 38px;
}
.options{
    cursor: pointer;
    font-size: small;
}
.options:hover{
    color: rgb(255, 75, 75);
}
</style>
    